//
//  IcAntiIcingTipsViewController.m
//  IceClear
//
//  Created by P & C on 2/23/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "IcAntiIcingTipsViewController.h"
#import "IcMaterial.h"


@implementation IcAntiIcingTipsViewController

@synthesize appModelsManager;


/*
// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
		//.....
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	NSMutableString* strBuilder = [NSMutableString string];
	NSMutableArray* vals = [NSMutableArray array];
	NSMutableArray* labels = [NSMutableArray array];
	
	for (NSNumber * n in [[self.appModelsManager.recommendationsManager.liquidSaltingRates allValues] reverseObjectEnumerator]) {
		[vals addObject:[NSString stringWithFormat:@"%d", [n intValue]]];
	}
	for (NSNumber * n in [self.appModelsManager.recommendationsManager.liquidSaltingRates allKeys]) {
		[labels addObject:[NSString stringWithFormat:@"%d", [n intValue]]];
	}
	
	/*[strBuilder appendString:@"https://chart.googleapis.com/chart?chs=280x220&cht=lxy"];
	[strBuilder appendString:@"&chtt=Salting+Rates&chts=660000,12"];
	//[strBuilder appendString:@"&chf=bg,lg,0,808080,0,EFEFEF,1|c,lg,0,E5ECF9,0,C3D9FF,1"]; // chart bg colors
	[strBuilder appendString:@"&chco=3072F3"]; // color of different data series
	[strBuilder appendString:@"&chxt=y,x,y,x&chxr=0,0,30|1,-35,0|2,0,30|3,-35,0"]; // kinds of axis and their range
	//[strBuilder appendString:@"&chxs=0,AA0033,11,0,l,676767|1,224499,9,0,l,676767|2,AA0033,11,0,l,676767|3,224499,9,0,l,676767"]; // styling of axis
	[strBuilder appendString:@"&chg=0,17,0,0"]; // chart grids*/
	
	[strBuilder appendString:@"http://chart.apis.google.com/chart?chxl=2:|litres%2Fm2|3:|Pavement+Temp+(C)&chxp=2,15|3,-18&chxr=0,0,30|1,-35,0|2,0,30|3,-35,0&chxt=y,x,y,x&chs=280x200&cht=lxy&chco=3072F3&chds=0,30,0,30&chdl=Salt+Amount&chdlp=b&chg=0,17,0,0&chls=2&chma=5,5,5,25|0,14&chtt=Salting+Rates&chts=660000,12"];
	
	[strBuilder appendFormat:@"&chd=t:-1|%@", [vals componentsJoinedByString:@","]];
	/*[strBuilder appendString:@"&chds=0,30"];
	[strBuilder appendString:@"&chdl=Salt|Amount"];
	[strBuilder appendFormat:@"&chxl=2:|kg+per|100+sq+m|3:|Pavement+Temp+(C)"];
	[strBuilder appendString:@"&chxp=2,17|3,-18"];*/
	
	// finalize the google charts api url
	NSString* googleChartsUrl = [NSString stringWithFormat:@"%@", strBuilder];
	//googleChartsUrl = @"http://chart.apis.google.com/chart?chxl=2:|kg%2Fm2|3:|Pavement+Temp+(C)&chxp=2,15|3,-18&chxr=0,0,30|1,-35,0|2,0,30|3,-35,0&chxt=y,x,y,x&chs=280x200&cht=lxy&chco=3072F3&chds=0,30,0,30&chd=t:-1|28,20,12,5&chdl=Salt+Amount&chdlp=b&chg=0,10,0,0&chls=2&chma=5,5,5,25|0,14&chtt=Salting+Rates&chts=660000,12";
	NSLog(@"Google charts url: %@", googleChartsUrl);
	
	// put it in a html string
	NSString* htmlFormat = @"<html><head><title>None</title></head><body><center><img src=\"%@\" /></center></body>";
	NSString* html = [NSString stringWithFormat:htmlFormat, googleChartsUrl];
	
	// grab materials that are good for ant-icing from our material models manager
	IcMaterial* m1 = [self.appModelsManager.materialsManager materialNamed:@"nacl-liquid"];
	IcMaterial* m2 = [self.appModelsManager.materialsManager materialNamed:@"cacl-liquid"];
	IcMaterial* m3 = [self.appModelsManager.materialsManager materialNamed:@"mgcl-liquid"];
	
	// set up the data of the table view with each section and its rows
	// first element will be the title of the section while the second
	// will hold the date used to build the cells of the different rows
	NSArray* introSection = [NSArray arrayWithObjects:@"", [NSArray arrayWithObject:@"    Anti-icing chemicals are to be applied before snow or ice storms in order to prevent or delay the formation of ice, or the adhesion of ice and snow to the pavement."], nil]; 
	NSArray* materialsSection = [NSArray arrayWithObjects:@"Materials", [NSArray arrayWithObject:@"Fluids are the most commonly used materials for anti-icing.\nLiquid salt is the most effective for temperatures above -10 C. Below that, the most common fluid is a mixture of water and salt called brine which is effective to -21 C. It is possible to get equipment to make your own brine.\nOther fluids include calcium chloride, magnesium chloride, potassium acetate, potassium chloride and calcium magnesium acetate."], nil];
	NSArray* productsSection = [NSArray arrayWithObjects:@"Recommended Products", 
								[NSArray arrayWithObjects:[m1.suggestedProducts objectAtIndex:0], 
								 [m2.suggestedProducts objectAtIndex:0], [m3.suggestedProducts objectAtIndex:0],
								 nil], 
								nil];
	NSArray* ratesSection = [NSArray arrayWithObjects:@"Application Rates", [NSArray arrayWithObject:html], nil];
	tblTipsData = [[NSMutableArray array] retain];
	
	// add different sections together into one wrapping array
	[tblTipsData addObject:introSection];
	[tblTipsData addObject:materialsSection];
	[tblTipsData addObject:productsSection];
	[tblTipsData addObject:ratesSection];
	
	self.view.backgroundColor = [UIColor clearColor];
	lblHeading.backgroundColor = [UIColor clearColor];
	tblTips.backgroundColor = [UIColor clearColor];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


#pragma mark -
#pragma mark UITableView delegation

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	//if (tableView.tag == 0) {
		return [self numberOfSectionsInTableViewForTblTips: tableView];
	//}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	//if (tableView.tag == 0) {
		return [self numberOfRowsInSectionForTblTips: section];
	//}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	//if (tableView.tag == 0) {
		return [self cellForRowAtIndexPathForTblTips: indexPath];
	//}
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	//if (tableView.tag == 0) {
		return [self titleForHeaderInSectionForTblTips: section];
	//}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	//if (tableView.tag == 0) {
		return [self heightForRowAtIndexPathForTblTips: indexPath];
	//}
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//if (tableView.tag == 0) {
		return [self didSelectRowAtIndexPathForTblTips: indexPath];
	//}
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//if (tableView.tag == 0) {
		return [self willSelectRowAtIndexPathForTblTips: indexPath];
	//}
}


- (NSInteger)numberOfSectionsInTableViewForTblTips:(UITableView *)tableView {
	return [tblTipsData count];
}

- (NSInteger)numberOfRowsInSectionForTblTips:(NSInteger)section {
	return [[[tblTipsData objectAtIndex:section] objectAtIndex:1] count];
}

- (CGFloat)heightForRowAtIndexPathForTblTips:(NSIndexPath *)indexPath {
	float val = 200;
	
	switch (indexPath.section) {
		case 0:
			val = 100;
			break;
		case 2:
			val = 30;
			break;
		case 3:
			val = 250;
			break;

		default:
			break;
	}
	
	return val;
}

- (void)didSelectRowAtIndexPathForTblTips:(NSIndexPath *)indexPath {
	if (indexPath.section == 2) {
		// when a recommended product is clicked launch the browser
		// to that product's web site
		[[UIApplication sharedApplication] openURL:[[[[tblTipsData objectAtIndex:indexPath.section] objectAtIndex:1] 
													 objectAtIndex:indexPath.row] objectAtIndex:1]];
	}
}

- (UITableViewCell *)cellForRowAtIndexPathForTblTips:(NSIndexPath *)indexPath {
	static NSString* tblCellIdentifier = @"identifier.tbl.reuseablecell";
	static NSString* tblCellIdentifier2 = @"identifier.tbl.reuseablecell.withwebview";
	
    UITableViewCell* cell = [tblTips dequeueReusableCellWithIdentifier:tblCellIdentifier];
	
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tblCellIdentifier] autorelease];
    }
	
	// customize the cell
	
	if (indexPath.section == 2) {
		// the third section is about the recommended products
		// the format of the data source for this section is:
		// - Root (Array)
		//		- Products Section (Array)
		//			- Title (String)
		//			- Products (Array)
		//				- Product (Array)
		//					- Name (String)
		//					- Url (URL)
		cell.textLabel.text = [[[[tblTipsData objectAtIndex:indexPath.section] objectAtIndex:1] objectAtIndex:indexPath.row] 
							   objectAtIndex: 0];
	}
	else if (indexPath.section == 3) {
		cell = [tblTips dequeueReusableCellWithIdentifier:tblCellIdentifier2];
		
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tblCellIdentifier2] autorelease];
			
			UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(5, 5, 285, 230)];
			
			cell.textLabel.text = nil;
			
			// remove previously added subviews
			for (UIView *v in cell.contentView.subviews) {
				[v removeFromSuperview];
			}
			// add the web view to the content view
			[cell.contentView addSubview:webView];
			// load the html string
			[webView loadHTMLString:[[[tblTipsData objectAtIndex:indexPath.section] objectAtIndex:1] objectAtIndex:indexPath.row] 
							baseURL:[NSURL URLWithString:@"http://www.google.com"]];
			
			//[webView release];
		}
	}
    else {
		// the format of the data source for other sections is:
		// - Root (Array)
		//		- Any Other Section (Array)
		//			- Title (String)
		//			- Contents (Array)
		//				- Content (String)
		cell.textLabel.text = [[[tblTipsData objectAtIndex:indexPath.section] objectAtIndex:1] objectAtIndex:indexPath.row];
		cell.textLabel.numberOfLines = 0;
		cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
		cell.textLabel.font = [UIFont systemFontOfSize:13];
	}
	
    return cell;
}

- (NSString *)titleForHeaderInSectionForTblTips:(NSInteger)section {
	return [[tblTipsData objectAtIndex:section] objectAtIndex: 0];
}

- (NSIndexPath *)willSelectRowAtIndexPathForTblTips:(NSIndexPath *)indexPath {
	// only clicks on third section (recommended products)
	if (indexPath.section == 2) {
		return indexPath;
	}
	else {
		return nil;
	}

}


#pragma mark -
#pragma mark memory management

- (void)dealloc {
	[tblTips release];
	[tblTipsData release];
	[appModelsManager release];
	[lblHeading release];
    [super dealloc];
}


@end
